/**
 * 视频裁剪功能模块
 */

import { formatFileSize, formatDuration, showAlert, validateTimeFormat } from './utils.js';

let currentTaskId = null;

// 初始化事件监听
document.addEventListener('DOMContentLoaded', function() {
    // 表单提交
    const cutForm = document.getElementById('cut-form');
    if (cutForm) {
        cutForm.addEventListener('submit', handleCutFormSubmit);
    }

    // 重命名对话框
    const renameDialog = document.getElementById('rename-dialog');
    if (renameDialog) {
        // 显示重命名对话框
        const renameBtn = document.querySelector('.rename-btn');
        if (renameBtn) {
            renameBtn.addEventListener('click', showRenameDialog);
        }

        // 隐藏重命名对话框
        const cancelBtn = renameDialog.querySelector('[data-action="hide-rename-dialog"]');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', hideRenameDialog);
        }

        // 确认重命名
        const confirmBtn = renameDialog.querySelector('[data-action="confirm-rename"]');
        if (confirmBtn) {
            confirmBtn.addEventListener('click', renameVideo);
        }
    }

    // 下载视频
    const downloadBtn = document.querySelector('.download-btn');
    if (downloadBtn) {
        downloadBtn.addEventListener('click', downloadVideo);
    }
});

// 处理裁剪表单提交
export async function handleCutFormSubmit(e) {
    e.preventDefault();
    
    const videoFile = document.getElementById('video-file').files[0];
    const startTime = document.getElementById('start-time').value;
    const endTime = document.getElementById('end-time').value;
    
    if (!videoFile) {
        showAlert('请选择视频文件');
        return;
    }
    
    if (!startTime || !endTime) {
        showAlert('请输入开始和结束时间');
        return;
    }
    
    if (!validateTimeFormat(startTime) || !validateTimeFormat(endTime)) {
        showAlert('时间格式不正确，请使用HH:MM:SS格式');
        return;
    }
    
    const formData = new FormData();
    formData.append('video', videoFile);
    formData.append('start_time', startTime);
    formData.append('end_time', endTime);
    
    try {
        const cutProgress = document.getElementById('cut-progress');
        const currentStep = document.getElementById('current-step');
        const loadingSpinner = document.getElementById('loading-spinner');
        
        cutProgress.style.display = 'block';
        currentStep.textContent = '正在上传视频...';
        loadingSpinner.style.display = 'inline-block';
        
        const response = await fetch('/api/cut', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.error) {
            throw new Error(data.error);
        }
        
        currentTaskId = data.task_id;
        pollProgress(data.task_id);
        
    } catch (error) {
        console.error('裁剪失败:', error);
        showAlert('裁剪失败: ' + error.message);
        document.getElementById('cut-progress').style.display = 'none';
    }
}

// 轮询进度
function pollProgress(taskId) {
    fetch(`/api/cut/progress/${taskId}`)
        .then(response => response.json())
        .then(data => {
            const progressBar = document.getElementById('progress-bar');
            const currentStep = document.getElementById('current-step');
            const cutStatus = document.getElementById('cut-status');
            const loadingSpinner = document.getElementById('loading-spinner');
            
            if (data.status === 'finished') {
                progressBar.style.width = '100%';
                progressBar.textContent = '100%';
                progressBar.className = 'progress-bar bg-success';
                
                currentStep.textContent = '裁剪完成';
                cutStatus.textContent = '状态: 已完成';
                loadingSpinner.style.display = 'none';
                
                document.getElementById('cut-progress').style.display = 'none';
                showResult();
                return;
            }
            
            if (data.status === 'error') {
                currentStep.textContent = `裁剪失败: ${data.error}`;
                cutStatus.textContent = '状态: 失败';
                progressBar.className = 'progress-bar bg-danger';
                loadingSpinner.style.display = 'none';
                return;
            }
            
            progressBar.style.width = `${data.progress}%`;
            progressBar.textContent = `${data.progress}%`;
            
            currentStep.textContent = data.current_step || '正在裁剪...';
            cutStatus.textContent = `状态: ${data.status === 'running' ? '处理中' : '等待中'}`;
            
            setTimeout(() => pollProgress(taskId), 1000);
        })
        .catch(error => {
            console.error('获取进度失败:', error);
            document.getElementById('current-step').textContent = '获取进度失败';
            document.getElementById('cut-status').textContent = '状态: 错误';
            document.getElementById('progress-bar').className = 'progress-bar bg-danger';
            document.getElementById('loading-spinner').style.display = 'none';
        });
}

// 显示结果
async function showResult() {
    try {
        const response = await fetch(`/api/cut/preview/${currentTaskId}`);
        const data = await response.json();
        
        const video = document.getElementById('preview-video');
        video.src = data.url;
        
        document.getElementById('video-filename').textContent = data.filename;
        document.getElementById('video-size').textContent = formatFileSize(data.size);
        document.getElementById('video-duration').textContent = formatDuration(data.duration);
        
        const downloadBtn = document.querySelector('.download-btn');
        downloadBtn.setAttribute('data-filename', data.filename);
        
        document.querySelector('.progress-section').style.display = 'none';
        document.querySelector('.result-section').style.display = 'block';
    } catch (error) {
        console.error('获取预览信息失败：', error);
    }
}

// 重命名相关功能
export function showRenameDialog() {
    const currentName = document.getElementById('video-filename').textContent;
    document.getElementById('new-filename').value = currentName.replace('.mp4', '');
    document.getElementById('rename-dialog').style.display = 'flex';
}

export function hideRenameDialog() {
    document.getElementById('rename-dialog').style.display = 'none';
}

export async function renameVideo() {
    const newName = document.getElementById('new-filename').value;
    if (!newName) {
        showAlert('请输入文件名');
        return;
    }

    try {
        const response = await fetch(`/api/cut/rename/${currentTaskId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `new_name=${encodeURIComponent(newName)}`
        });
        
        const data = await response.json();
        if (data.status === 'success') {
            document.getElementById('video-filename').textContent = data.new_filename;
            const downloadBtn = document.querySelector('.download-btn');
            downloadBtn.setAttribute('data-filename', data.new_filename);
            hideRenameDialog();
        } else {
            showAlert('重命名失败：' + data.error);
        }
    } catch (error) {
        console.error('重命名失败：', error);
        showAlert('重命名失败，请重试');
    }
}

// 下载视频
export function downloadVideo() {
    const downloadBtn = document.querySelector('.download-btn');
    const filename = downloadBtn.getAttribute('data-filename') || '';
    const url = `/api/cut/file/${currentTaskId}`;
    
    const a = document.createElement('a');
    a.href = url;
    if (filename) {
        a.download = filename;
    }
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
